﻿using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using PMS.BLL;
using PMS.Entity;
using PMS.Resources;
using PMS.Win;
using PMS.Utils;
using DevExpress.XtraEditors.Mask;
using PMS.DanhMucChung;
using System.Collections.Generic;
using PMS.ValidationRules;
using PMS.ReportViewer;
using DevExpress.XtraGrid.Views.Base;
using System.Drawing;

namespace PMS.ChucNang
{
    public partial class ThanhToanEntry : FormEntryBase
    {
        #region Constants
        private const string CTPXKHONGTONTAI = "CTPXKHONGTONTAI";
        private const string ThanhToanPhaiLonHon0 = "ThanhToanPhaiLonHon0";
        private const string QTY_NOT_GREAT_THAN = "QTY_NOT_GREAT_THAN";
        private const string DUPLICATE_PRODUCT_CODE = "DUPLICATE_PRODUCT_CODE";
        private const string CHITITENHAP_DONOT_EXISTED = "CHITITENHAP_DONOT_EXISTED";
        private const string MUST_FILL_HANDUNG_OR_HANSUDUNG = "MUST_FILL_HANDUNG_OR_HANSUDUNG";
        private string TongSoTienThanhToanVuotQuaSoTienHoaDon = "TongSoTienThanhToanVuotQuaSoTienHoaDon";

        private string NEW_String = Messages.GetString(Constants.NEW);
        private const string BINDING_PROPERTY = "EditValue";
        #endregion

        #region Private Members
        BaseEntityCollection<ThanhToan> m_DetailItemsList;
        private List<ComboItemExp> m_KhoList;
        protected SanPhamBO m_ProductService;
        protected PhieuXuatBO m_Service;
        protected KhachHangBO m_KHService;
        protected ThanhToanBO m_ChiTietService;
        protected ThanhToanBO m_ThanhToanService;

        protected ThanhToan ThanhToanSelected;
        
        
        protected bool m_isDuplicateProduct { get; set; }
        #endregion

        #region Properties
        protected Entity.PhieuXuat CurrentNhapKhoEntry
        {
            get
            {
                return base.Entity as Entity.PhieuXuat;
            }
            set
            {
                base.Entity = value;
            }
        }

        #endregion

        #region Services

        public ThanhToanBO ThanhToanService
        {
            get
            {
                if (m_ThanhToanService == null)
                {
                    m_ThanhToanService = new ThanhToanBO();
                }
                return m_ThanhToanService;
            }
        }

        public KhachHangBO KHService
        {
            get
            {
                if (m_KHService == null)
                {
                    m_KHService = new KhachHangBO();
                }
                return m_KHService;
            }
        }

        public PhieuXuatBO Service
        {
            get
            {
                if (m_Service == null)
                {
                    m_Service = new PhieuXuatBO();
                }
                return m_Service;
            }
        }

        public SanPhamBO ProductService
        {
            get
            {
                if (m_ProductService == null)
                {
                    m_ProductService = new SanPhamBO();
                }
                return m_ProductService;
            }
        }

        public ThanhToanBO ChiTietService
        {
            get
            {
                if (m_ChiTietService == null)
                {
                    m_ChiTietService = new ThanhToanBO();
                }
                return m_ChiTietService;
            }
        }
        #endregion

        #region Constructors
        public ThanhToanEntry(string functionID)
            : base(functionID)
        {
            InitializeComponent();
            Init();
        }
        #endregion

        #region Init Data and Style
        private void Init()
        {
            InitData();
            InitStyle();
        }

        private void InitData()
        {
            m_DetailItemsList = new BaseEntityCollection<ThanhToan>();
            BindingToGrid();
            loadDatasourceCbbKho();
        }

        private void InitStyle()
        {
            //grid
            grdDetail.CausesValidation = false;
            bteMaPN.Tag = "Ignore";

            this.grvDetail.OptionsView.ShowFooter = true;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsView.ShowGroupPanel = true;
            this.grvDetail.OptionsCustomization.AllowColumnMoving = false;
            this.grvDetail.OptionsCustomization.AllowGroup = true;
            this.grvDetail.OptionsMenu.EnableColumnMenu = false;
            this.grvDetail.OptionsMenu.EnableFooterMenu = false;
            this.grvDetail.OptionsNavigation.EnterMoveNextColumn = true;
            this.grvDetail.OptionsView.ShowFilterPanelMode = DevExpress.XtraGrid.Views.Base.ShowFilterPanelMode.Never;
            this.grvDetail.IndicatorWidth = Constants.INDICATOR_WIDTH;
            this.grvDetail.OptionsView.NewItemRowPosition = DevExpress.XtraGrid.Views.Grid.NewItemRowPosition.Bottom;

            cbbMaKho.Properties.TextEditStyle = DevExpress.XtraEditors.Controls.TextEditStyles.DisableTextEditor;
            cbbMaKho.Properties.ReadOnly = true;
            txtTongTien.Properties.ReadOnly = true;

            //filed color
            cbbMaKho.Properties.ReadOnly = true;
            txtSoHD.Properties.ReadOnly = true;
            txtNguoiLap.Properties.ReadOnly = true;
            dteNgayLap.Properties.ReadOnly = true;
            txtNguoiNhap.Properties.ReadOnly = true;
            dteNgayNhap.Properties.ReadOnly = true;
            txtTongTien.Properties.ReadOnly = true;
            txtDaThanhToan.Properties.ReadOnly = true;
            txtLyDo.Properties.ReadOnly = true;
            txtGhiChu.Properties.ReadOnly = true;
            bteNhaCC.Properties.ReadOnly = true;

            txtTenKH.Properties.ReadOnly = true;
            txtDiaChi.Properties.ReadOnly = true;
            txtSoDT.Properties.ReadOnly = true;
            txtFax.Properties.ReadOnly = true;
            txtMST.Properties.ReadOnly = true;
            txtEmail.Properties.ReadOnly = true;

            bteMaPN.BackColor = REQUIRED_FIELD_COLOR;
            cbbMaKho.BackColor = DISABLE_FIELD_COLOR;
            txtSoHD.BackColor = DISABLE_FIELD_COLOR;
            txtNguoiLap.BackColor = DISABLE_FIELD_COLOR;
            dteNgayLap.BackColor = DISABLE_FIELD_COLOR;
            txtNguoiNhap.BackColor = DISABLE_FIELD_COLOR;
            dteNgayNhap.BackColor = DISABLE_FIELD_COLOR;
            txtTongTien.BackColor = DISABLE_FIELD_COLOR;
            txtDaThanhToan.BackColor = DISABLE_FIELD_COLOR;
            txtLyDo.BackColor = DISABLE_FIELD_COLOR;
            txtGhiChu.BackColor = DISABLE_FIELD_COLOR;
            bteNhaCC.BackColor = DISABLE_FIELD_COLOR;

            txtTenKH.BackColor = DISABLE_FIELD_COLOR;
            txtDiaChi.BackColor = DISABLE_FIELD_COLOR;
            txtSoDT.BackColor = DISABLE_FIELD_COLOR;
            txtFax.BackColor = DISABLE_FIELD_COLOR;
            txtMST.BackColor = DISABLE_FIELD_COLOR;
            txtEmail.BackColor = DISABLE_FIELD_COLOR;

            //Mask
            txtTongTien.Properties.Mask.MaskType = MaskType.Numeric;
            txtTongTien.Properties.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            txtTongTien.Properties.Mask.UseMaskAsDisplayFormat = true;

            txtDaThanhToan.Properties.Mask.MaskType = MaskType.Numeric;
            txtDaThanhToan.Properties.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            txtDaThanhToan.Properties.Mask.UseMaskAsDisplayFormat = true;

            this.bteMaPN.Properties.MaxLength = 14;

            repositoryItemTextEdit1.Mask.MaskType = MaskType.Numeric;
            repositoryItemTextEdit1.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            repositoryItemTextEdit1.Mask.UseMaskAsDisplayFormat = true;

            repositoryItemTextEdit2.Mask.MaskType = MaskType.Numeric;
            repositoryItemTextEdit2.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            repositoryItemTextEdit2.Mask.UseMaskAsDisplayFormat = true;

            repositoryItemTextEdit3.Mask.MaskType = MaskType.Numeric;
            repositoryItemTextEdit3.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            repositoryItemTextEdit3.Mask.UseMaskAsDisplayFormat = true;

            repositoryItemTextEdit4.Mask.MaskType = MaskType.Numeric;
            repositoryItemTextEdit4.Mask.EditMask = ConfigurationConstant.PositiveNumericFormatString;
            repositoryItemTextEdit4.Mask.UseMaskAsDisplayFormat = true;

        }
        #endregion

        #region override methods

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            if (this.CurrentNhapKhoEntry == null)
            {
                this.DoNew();
            }
        }

        protected override void BindingToControls(IBaseEntity entity)
        {
            base.BindingToControls(entity);

            this.bteMaPN.DataBindings.Clear();
            this.txtSoHD.DataBindings.Clear();
            this.txtNguoiLap.DataBindings.Clear();
            this.dteNgayLap.DataBindings.Clear();
            this.txtNguoiNhap.DataBindings.Clear();
            this.dteNgayNhap.DataBindings.Clear();
            this.txtLyDo.DataBindings.Clear();
            this.txtGhiChu.DataBindings.Clear();


            this.bteMaPN.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.SoPX.ToString());
            this.txtSoHD.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.SoHD.ToString());
            this.txtNguoiLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NguoiLap.ToString());
            this.dteNgayLap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NgayLapPhieu.ToString());
            this.txtNguoiNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NguoiXuat.ToString());
            this.dteNgayNhap.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.NgayXuatKho.ToString());
            this.txtLyDo.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.LyDoXuat.ToString());
            this.txtGhiChu.DataBindings.Add(BINDING_PROPERTY, entity, PhieuXuatColumns.GhiChu.ToString());

            PhieuXuat pn = entity as PhieuXuat;
            m_DetailItemsList.Clear();
            m_DetailItemsList.AddRange(ThanhToanService.GetAllThanhToanBySoPX(pn.SoPX));
            BindingToGrid();
            SetKhoCbbData(pn.MaKho);


            PhieuGiaoHang pg = (new PhieuGiaoHangBO()).GetPhieuGiaoHangBySoPX(CurrentNhapKhoEntry.SoPX);

            KhachHang khachhang = null;
            if (pg != null)
            {
                khachhang = KHService.GetKhachHangByID(pg.MaKH);
            }


            if (khachhang == null)
            {
                khachhang = new KhachHang();
            }

            this.txtTenKH.DataBindings.Clear();
            this.txtDiaChi.DataBindings.Clear();
            this.txtSoDT.DataBindings.Clear();
            this.txtFax.DataBindings.Clear();
            this.txtEmail.DataBindings.Clear();
            this.txtMST.DataBindings.Clear();
            this.bteNhaCC.DataBindings.Clear();

            this.txtTenKH.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.TenKH.ToString());
            this.txtDiaChi.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.DiaChi.ToString());
            this.txtSoDT.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.SoDT.ToString());
            this.txtFax.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.SoFax.ToString());
            this.txtEmail.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.Email.ToString());
            this.txtMST.DataBindings.Add(BINDING_PROPERTY, khachhang, KhachHangColumns.MaSoThue.ToString());
            this.bteNhaCC.DataBindings.Add(BINDING_PROPERTY, khachhang, PhieuXuatColumns.MaKH.ToString());

            if (m_DetailItemsList.Count > 0)
            {
                long total = 0;
                foreach (ThanhToan item in m_DetailItemsList)
                {

                    total = total + item.SoTien;
                }
                txtDaThanhToan.EditValue = total;
            }
            else
            {
                txtDaThanhToan.EditValue = 0;
            }

            ChiTietPhieuXuats xuarList = (new ChiTietPhieuXuatBO()).GetAllChiTietPhieuXuatBySoPX(CurrentNhapKhoEntry.SoPX);
            long totalXuat = 0;
            foreach (var item in xuarList)
            {
                totalXuat = totalXuat + item.Total;
            }

            txtTongTien.EditValue = totalXuat;
        }

        protected override void FocusFirtsControl()
        {
            base.FocusFirtsControl();
            this.txtSoHD.Focus();
        }

        protected override void InitValidationRules()
        {
            base.InitValidationRules();
            Validator validate = new Validator(ValidationProvider);
            validate.AddValidationRule(new PhieuXuatValidateRule(null, false));
            SetValidator(validate, bteMaPN);

        }

        public override void New()
        {
            this.CurrentNhapKhoEntry = new Entity.PhieuXuat();
            txtTongTien.EditValue = 0;
            base.New();
        }

        protected override bool Save()
        {
            try
            {
                foreach (ThanhToan tt in m_DetailItemsList)
                {
                    if (string.IsNullOrEmpty(tt.MaTT))
                    {
                        ThanhToanService.CreateThanhToan(tt);
                    }
                }

                foreach (ThanhToan item in m_DetailItemsList.RemoveRows)
                {
                    ThanhToanService.DeleteThanhToan(item);
                }

                CurrentNhapKhoEntry = CurrentNhapKhoEntry;
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        protected override bool Delete()
        {
            //ShowErrorMessage(Messages.GetString("JustDeleteRow"));
            //return false;
            try
            {
                ThanhToanService.DeleteThanhToan(ThanhToanSelected);
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }

        public override void Cancel()
        {
            //your code here
            base.Cancel();
        }

        protected override void Print()
        {
           
        }

        protected override IBaseEntity GetEntity()
        {
            //need to get the latest record of the current Entity's ID or code then return it
            return base.GetEntity();
        }
        #endregion

        #region Lookups
        #endregion

        #region Form's function

        private void BindingToGrid()
        {
            grdDetail.DataSource = m_DetailItemsList;
            colMaThuoc.FieldName = LuuKhoColumns.MaThuoc.ToString();
            colThanhToan.FieldName = ThanhToanColumns.SoTien.ToString();
            colDonGia.FieldName = ChiTietPhieuXuatColumns.DonGia.ToString();
            colSolo.FieldName = LuuKhoColumns.SoLo.ToString();
            colMaCTPX.FieldName = ThanhToanColumns.MaCTPX.ToString();
            colSoluong.FieldName = ChiTietPhieuXuatColumns.SoLuong.ToString();
            colGhiChu.FieldName = ThanhToanColumns.GhiChu.ToString();
            colNgayTT.FieldName = ThanhToanColumns.NgayTT.ToString();
            colThanhTien.FieldName = ChiTietPhieuXuatColumns.Total.ToString();
            colPTTT.FieldName = ThanhToanColumns.PhuongThucTT.ToString();
        }

        private void LoadingProductToGrid(ChiTietPhieuXuat loadingProduct)
        {
            ThanhToan getRow = grvDetail.GetFocusedRow() as ThanhToan;
            bool isNewRow = false;
            if (getRow == null)
            {
                isNewRow = true;
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }
            else if (grvDetail.FocusedRowHandle < 0)
            {
                isNewRow = true;
                m_DetailItemsList.RemoveAt(m_DetailItemsList.Count - 1);
                m_DetailItemsList.RemoveRows.Remove(getRow);
                getRow = m_DetailItemsList.AddNew();
                grvDetail.FocusedRowHandle = m_DetailItemsList.Count - 1;
            }

            ClearStatusMessage();
            grvDetail.ClearColumnErrors();

            getRow.MaCTPX = loadingProduct.MaCTPX;
            getRow.NgayTT = Constants.BUSINESS_DATE;
            getRow.SoLo = loadingProduct.SoLo;
            getRow.DonGia = loadingProduct.DonGia;
            getRow.SoLuong = loadingProduct.SoLuong;
            getRow.GiaTrungThau = loadingProduct.GiaTrungThau;

            getRow.MaThuoc = loadingProduct.MaThuoc;
            grvDetail.SetFocusedRowCellValue(colThanhToan, 0);
            grvDetail.FocusedRowHandle = grvDetail.GetRowHandle(m_DetailItemsList.IndexOf(getRow));
            if (isNewRow == true)
            {
                getRow.CreatedDate = DateTime.Now;
                getRow.RowStatus = (byte)RowStatus.New;
            }
            grvDetail.RefreshEditor(true);
            grvDetail.FocusedColumn = grvDetail.VisibleColumns[0];
        }

        private void LoadObjectOnForm(string previousCode, string code, IBaseEntity ObjectLoad)
        {
            if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
            {
                if (IsNew)
                {
                    if (ObjectLoad != null)
                    {
                        if (IsDataChanged)
                        {
                            var result = ShowSaveConfimMessage();
                            if (result == DialogResult.Yes)
                            {
                                CurrentNhapKhoEntry.SoPX = previousCode;
                                if (!base.ValidateControls() || !Save())
                                {
                                    return;
                                }
                            }
                        }
                        Entity = ObjectLoad;
                        IsNew = false;
                        IsDataChanged = false;
                    }
                    else
                    {
                        CurrentNhapKhoEntry.SoPX = code;
                        Entity = CurrentNhapKhoEntry;
                        IsNew = true;//important
                        IsDataChanged = true;//important                        
                    }
                }
                else
                {
                    if (!IsDataChanged)
                    {
                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuXuat();
                            CurrentNhapKhoEntry.SoPX = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry;
                            IsNew = true;//important
                            IsDataChanged = true;//important   
                        }
                    }
                    else
                    {
                        var result = ShowSaveConfimMessage();
                        if (result == DialogResult.Yes)
                        {
                            CurrentNhapKhoEntry.SoPX = previousCode;
                            if (!base.ValidateControls() || !Save())
                            {
                                return;
                            }
                        }

                        if (ObjectLoad != null)
                        {
                            Entity = ObjectLoad;
                            IsNew = false;
                            IsDataChanged = false;
                        }
                        else
                        {
                            CurrentNhapKhoEntry = new PhieuXuat();
                            CurrentNhapKhoEntry.SoPX = code;
                            //m_CurrentMaterial.Active = true;
                            Entity = CurrentNhapKhoEntry; ;
                            IsNew = true;//important
                            IsDataChanged = true;//important 
                        }
                    }
                }
                ClearErrorMessage();
            }
        }

        private void loadDatasourceCbbKho()
        {
            KhoHangs list = (new KhoHangBO()).GetAllKhoHang();
            m_KhoList = new List<ComboItemExp>();
            foreach (var item in list)
            {
                ComboItemExp tem = new ComboItemExp();
                tem.DisplayValue = item.TenKho;
                tem.ItemValue = item.MaKho;
                m_KhoList.Add(tem);
            }

            cbbMaKho.Properties.Items.AddRange(m_KhoList);
        }

        private void SetKhoCbbData(string code)
        {
            cbbMaKho.SelectedItem = m_KhoList.Find(o => o.ItemValue.ToString().Equals(code,StringComparison.CurrentCultureIgnoreCase));
        }
        #endregion

        private void bteMaPN_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                var form = new XuatKhoLookup(true);
                if (form.ShowDialog() == DialogResult.OK)
                {
                    IsNew = false;
                    if (form.PhieuXuatSelected != null)
                    {
                        LoadObjectOnForm(bteMaPN.Text.Trim(), form.PhieuXuatSelected.SoPX, form.PhieuXuatSelected);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void bteMaPN_Leave(object sender, EventArgs e)
        {
            try
            {
                if (string.IsNullOrEmpty(bteMaPN.Text)&&!IsNew)
                {
                    New();
                }
                else
                {
                    if (CurrentNhapKhoEntry == null) return;
                    string previousCode = DataConvertUltils.ToString(CurrentNhapKhoEntry.SoPX);
                    string code = DataConvertUltils.ToString(bteMaPN.EditValue);
                    if (!previousCode.Equals(code, StringComparison.OrdinalIgnoreCase))
                    {
                        PhieuXuat temPhieuXuat = Service.GetPhieuXuatByID(code);
                        LoadObjectOnForm(previousCode, code, temPhieuXuat);
                    }
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }


        private void grvDetail_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if ((e.Info.IsRowIndicator) && (e.RowHandle >= 0))
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        private void grvDetail_InvalidRowException(object sender, DevExpress.XtraGrid.Views.Base.InvalidRowExceptionEventArgs e)
        {
            e.ExceptionMode = DevExpress.XtraEditors.Controls.ExceptionMode.NoAction;
        }

        private void grvDetail_KeyDown(object sender, KeyEventArgs e)
        {
            ThanhToan row = grvDetail.GetFocusedRow() as ThanhToan;
            if (e.KeyCode == Keys.Delete)
            {
                if (this.grvDetail.IsRowSelected(this.grvDetail.FocusedRowHandle) == true)
                {
                    ThanhToan delrow = (ThanhToan)this.grvDetail.GetRow(grvDetail.FocusedRowHandle);
                    int index = this.m_DetailItemsList.IndexOf(delrow);
                    if (index != -1)
                    {
                        bool isNewRow = (delrow.RowStatus == (byte)RowStatus.New);

                        this.m_DetailItemsList.RemoveAt(index);
                        if (isNewRow == true)
                        {
                            this.m_DetailItemsList.RemoveRows.Remove(delrow);
                        }
                        base.IsDataChanged = true;


                        decimal total = 0;
                        foreach (ThanhToan item in m_DetailItemsList)
                        {
                            total = total + item.Total;
                        }
                        txtTongTien.EditValue = total;
                    }
                }
            }
            else 
            if (e.KeyCode == Keys.F3)
            {
                if (this.grvDetail.FocusedColumn == this.colMaCTPX)
                {
                    if (row == null) return;
                    if (!string.IsNullOrEmpty(row.MaTT)) return;
                    bteColMaThuoc_ButtonClick(sender, new DevExpress.XtraEditors.Controls.ButtonPressedEventArgs(this.bteColMaThuoc.Buttons[0]));
                }
            }
        }

        private void grvDetail_ShowingEditor(object sender, System.ComponentModel.CancelEventArgs e)
        {
            ThanhToan row = grvDetail.GetFocusedRow() as ThanhToan;
            if (string.IsNullOrEmpty(CurrentNhapKhoEntry.SoPX))
            {
                e.Cancel = true;
                return;
            }
            if (row != null)
            {
                if (!string.IsNullOrEmpty(row.MaTT))
                {
                    e.Cancel = true;
                }
            }

        }

        private void grvDetail_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            ThanhToan currentRow = grvDetail.GetFocusedRow() as ThanhToan;
            DevExpress.XtraGrid.Columns.GridColumn errorColumn = null;
            if (currentRow != null)
            {
                if (string.IsNullOrEmpty(currentRow.MaCTPX))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                    errorColumn = colMaCTPX;
                }
                else
                {
                    ChiTietPhieuXuat temProduct = (new ChiTietPhieuXuatBO()).GetChiTietPhieuXuatByID(currentRow.MaCTPX);
                    if (temProduct == null)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(CTPXKHONGTONTAI);
                        errorColumn = colMaCTPX;
                    }
                }
            }else if (currentRow.SoTien <= 0)
            {
                e.Valid = false;
                grvDetail.SetColumnError(colThanhToan, Messages.GetString(ThanhToanPhaiLonHon0));
                errorColumn = colThanhToan;
            }

            if (errorColumn != null)
            {
                grvDetail.FocusedColumn = errorColumn;
            }
            else
            {
                decimal total = 0;
                foreach (ThanhToan item in m_DetailItemsList)
                {
                    total = total + item.SoTien;
                }
                txtDaThanhToan.EditValue = total;
            }
        }

        private void grvDetail_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            ThanhToan row = grvDetail.GetFocusedRow() as ThanhToan;
            if (grvDetail.FocusedColumn == colThanhToan)
            {
                int thanhtoan = DataConvertUltils.ToInt(e.Value);
                if (thanhtoan <= 0)
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(ThanhToanPhaiLonHon0);
                }

                long total = 0;
                foreach (ThanhToan item in m_DetailItemsList)
                {
                    if (row.MaCTPX.Equals(item.MaCTPX, StringComparison.CurrentCultureIgnoreCase))
                    {
                        total = total + item.SoTien;
                    }
                }

                if (row.Total < (total+thanhtoan))
                {
                    e.Valid = false;
                    e.ErrorText = string.Format(Messages.GetString(TongSoTienThanhToanVuotQuaSoTienHoaDon),row.Total-total);

                }
                
            }
            else if (grvDetail.FocusedColumn == colMaCTPX)
            {
                string ptt = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(ptt))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
            }
            else if (grvDetail.FocusedColumn == colMaCTPX)
            {
                string productCode = DataConvertUltils.ToString(e.Value);
                if (string.IsNullOrEmpty(productCode))
                {
                    e.Valid = false;
                    e.ErrorText = Messages.GetString(Constants.REQUIRE_FIELD);
                }
                else
                {
                    ChiTietPhieuXuat temProduct = (new ChiTietPhieuXuatBO()).GetChiTietPhieuXuatByID(productCode);
                    if (temProduct == null)
                    {
                        e.Valid = false;
                        e.ErrorText = Messages.GetString(CTPXKHONGTONTAI);
                    }
                    else
                    {
                        e.Value = temProduct.MaThuoc;
                        LoadingProductToGrid(temProduct);
                    }
                }
            }
           
        }

        private void bteColMaThuoc_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ChiTietXuatLookup form = new ChiTietXuatLookup(true, CurrentNhapKhoEntry.SoPX); ;
            if (form.ShowDialog() == DialogResult.OK)
            {
                if (form.ChiTietPhieuXuatSelected != null)
                {
                    LoadingProductToGrid(form.ChiTietPhieuXuatSelected);
                }
            }
        }

        private void bteMaPN_Enter(object sender, EventArgs e)
        {
            if (bteMaPN.Text.Equals(NEW_String))
            {
                bteMaPN.Text = string.Empty;
            }
        }

        private void grvDetail_DataSourceChanged(object sender, EventArgs e)
        {
            decimal total = 0;
            foreach (ThanhToan item in m_DetailItemsList)
            {
                total = total + item.SoTien;
            }
            txtDaThanhToan.EditValue = total;

        }

        private void cbbMaKho_SelectedValueChanged(object sender, EventArgs e)
        {
            CurrentNhapKhoEntry.MaKho = (string)((ComboItemExp)cbbMaKho.SelectedItem).ItemValue;
        }

        private void chkPhieuGiao_CheckedChanged(object sender, EventArgs e)
        {
        }

        private void grvDetail_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            ThanhToan row = grvDetail.GetRow(e.RowHandle) as ThanhToan;
            if (e.RowHandle >= 0)
            {
                if(row!=null)
                {
                    if (!string.IsNullOrEmpty(row.MaTT))
                    {
                        e.Appearance.BackColor = Color.WhiteSmoke;
                    }
                }
            }
        }

        private void grvDetail_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            ThanhToanSelected = this.grvDetail.GetFocusedRow() as ThanhToan;
        }

    }
}
